<template>
	<el-switch
		v-model="inputMp3ByID"
		active-text="通过KEY检索音频"
		inactive-text="通过名称检索音频"
		@change="setMp3ByID(inputMp3ByID)"
	>
	</el-switch>

	<br />

	<el-input v-model="inputApi" placeholder="请输入对接服务器地址">
		<template #prepend>API</template>
		<template #append>
			<el-button
				type="primary"
				:icon="Refresh"
				:loading="isLoading"
				@click="clickChangeApi"
			/>
		</template>
	</el-input>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { useConfig } from "@/store/config";
import { Refresh } from "@element-plus/icons-vue";
import { checkServer } from "@/utils/useRequest";
import { ElInput, ElButton, ElNotification } from "element-plus";

const { setApi, API, setMp3ByID, mp3ByID } = useConfig();

const inputApi = ref(API);
const isLoading = ref(false);
const inputMp3ByID = ref(mp3ByID);

function accessErr(msg?: string) {
	ElNotification({
		message: msg ? "服务器连接异常：" + msg : "服务器连接异常",
		type: "error",
	});

	setApi(API);
	inputApi.value = API;
}

function accessTimeout() {
	ElNotification({
		message: "服务器连接超时",
		type: "error",
	});

	setApi(API);
	inputApi.value = API;
}

function acesssOk() {
	ElNotification({
		message: "服务器连接正常",
		type: "success",
	});
}

function clickChangeApi() {
	setApi(inputApi.value);
	isLoading.value = true;

	checkServer().then((msg) => {
		switch (msg) {
			case "ok":
				acesssOk();
				break;
			case "err":
				accessErr();
				break;
			case "timeout":
				accessTimeout();
				break;
			default:
				accessErr(msg);
		}

		isLoading.value = false;
	});
}
</script>

<style scoped>
.el-switch {
	padding-bottom: 15px;
	margin-left: 5px;
}
</style>
